package com.funcablaze.func;

import com.funcablaze.component.control.Theme;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SystemThemeDetector {
	
	/**
	 * 检测系统主题
	 * @return 主题模式
	 */
	public static Theme.ThemeType detect() {
		String os = System.getProperty("os.name").toLowerCase();
		if (os.contains("win")) {
			return detectWindows();
		} else if (os.contains("mac")) {
			return detectMacOS();
		} else if (os.contains("nix") || os.contains("nux")) {
			return detectLinux();
		}
		return Theme.ThemeType.Default;
	}
	
	// Windows 检测
	private static Theme.ThemeType detectWindows() {
		if (Advapi32Util.registryValueExists(WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme")) {
			int value = Advapi32Util.registryGetIntValue(WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme");
			return value == 0 ? Theme.ThemeType.Dark : Theme.ThemeType.Light;
		}
		return Theme.ThemeType.Default;
	}
	
	// macOS 检测
	private static Theme.ThemeType detectMacOS() {
		try {
			Process process = Runtime.getRuntime().exec("defaults read -g AppleInterfaceStyle");
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String output = reader.readLine();
			return output != null && output.equalsIgnoreCase("Dark") ? Theme.ThemeType.Dark : Theme.ThemeType.Light;
		} catch (IOException e) {
			return Theme.ThemeType.Default;
		}
	}
	
	// Linux (GNOME) 检测
	private static Theme.ThemeType detectLinux() {
		try {
			Process process = Runtime.getRuntime().exec("gsettings get org.gnome.desktop.interface gtk-theme");
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String theme = reader.readLine().replaceAll("'", "");
			return theme.toLowerCase().contains("-dark") ?
						   Theme.ThemeType.Dark : Theme.ThemeType.Light;
		} catch (Exception e) {
			return Theme.ThemeType.Default;
		}
	}
}